<?php

namespace app\common\model\news;
use think\Model;
use fast\Tree;
class NewsCategory extends Model
{

    

    

    // 表名
    protected $name = 'news_category';


    public function getCreatetimeAttr($value)
    {
        $status = date('Y-m-d', $value);
        return $status;
    }

    public function news(){
        return $this->hasMany('news','category_id');
    }


    /**
     * 读取分类列表
     * @param string $type   指定类型
     * @param string $status 指定状态
     * @return array
     */
    public static function getList()
    {

        $tree = Tree::instance();
        $tree->init(collection(self::where(function ($query)  {
            $query->where('status', '=', 'normal');
        })->order('weigh', 'desc')->field('id,name,createtime,image,pid')->select())->toArray(), 'pid');
        $list= $tree->getTreeArray(0);
        return $list;
    }

    /**
     * 读取父级ID
     * @param string $type   指定类型
     * @param string $status 指定状态
     * @return array
     */
    public static function geFathertList()
    {
        $list=collection(self::where(function ($query)  {
            $query->where('status', '=', 'normal');
            $query->where('pid', '=', 0);
        })->order('weigh', 'desc')->field('id,name,createtime,image,pid')->select())->toArray();

        return $list;
    }



    /**
     * 读取指定ID下子分类
     * @param string $type   指定类型
     * @param string $status 指定状态
     * @return array
     */
    public static function getListId($id)
    {

        $list=collection(self::where(['status'=>'normal'])->where('pid',$id)->with(['news'=>function($query){
            $query->where('status','=','normal');
            $query->field('id,createtime,image,title,weigh,show_number,category_id,description');
            $query->order('weigh desc');
        }])->order('weigh', 'desc')->field('id,name,createtime,image,pid')->select())->toArray();

        return $list;
    }



    /**
     * 根据分类ID读取条线
     * @param string $type   指定类型
     * @param string $status 指定状态
     * @return array
     */
    public static function getLineList($data)
    {

        $info=self::where(function ($query)  {
            $query->where('status', '=', 'normal');
        })->order('weigh', 'desc');
        if(!empty($data['id'])){
            $info->where('id|pid','=',$data['id']);
        }
        $list=collection($info->field('id,name,createtime,image,pid')->select())->toArray();
        if(empty($list)){
            return $list;
        }
        $ids=[];
        foreach ($list as $k=>$v){
            $ids[]=$v['id'];
            $ids[]=$v['pid'];
        }

        $tree = Tree::instance();
        $tree->init(collection(self::where(function ($query)  {
            $query->where('status', '=', 'normal');
        })->where('id|pid','in',$ids)->order('weigh', 'desc')->field('id,name,createtime,image,pid')->select())->toArray(), 'pid');
        $list= $tree->getTreeArray(0);
        return $list;
    }



}
